<template>
  <div :style="styleObj">
    <div
      class="topology"
      id="topology"
      preview="true"
      :data="data"
      :key="topologyKey"
    ></div>
    <div class="tools">
      <div></div>
      <!-- <el-button type="primary" size="mini" style="margin-right: 0" @click="onSizeWindow">
        适合窗口
      </el-button>
      <el-button type="primary" size="mini" @click="onSizeOri">
        实际大小
      </el-button> -->
    </div>
    <!-- </div> -->
    <YKdialog ref="ykRef"></YKdialog>
    <YTdialog ref="ytRef"></YTdialog>
    <YTdialogAll ref="ytallRef"></YTdialogAll>
    <el-dialog
      :title="FangZhenTitle"
      :visible.sync="FangZhenDialogVisible"
      :width="DialogWidth"
      :close-on-click-modal="false"
      center
      custom-class="mydialog"
      :fullscreen="isFullscreen"
    >
      <div slot="title" class="headertitle">
        <span>{{ FangZhenTitle }} </span>
        <i class="el-icon-full-screen" @click="fullscreen"></i>
      </div>
      <timeReport
        :body="body"
        :header="header"
        :tableHeight="maxheight"
        :loadingShow="loadingShow"
        :getBodyData="getBodyData"
        :bodyConfigList="bodyConfigList"
        :getCellClassName="getCellClassName"
        :isShow="isFormat"
      ></timeReport>
    </el-dialog>
  </div>
</template>
<script>
import { DataMessage } from "@/utils/topolpgy/msg";
import store from "@/store/index.js";
import { defalutMaterials } from "@/utils/topolpgy/data";
import {
  setMessageCallback,
  getGuid32,
  publishMsg,
  removeMessageCallback,
  checkSpecialId,
} from "@/mqtt";

import timeReport from "@/components/Topology/timeReport.vue";
import YTdialog from "@/components/Topology/YTdialog.vue";
import YKdialog from "@/components/Topology/YKdialog.vue";
import YTdialogAll from "@/components/Topology/YTdialogAll.vue";
import { Topology } from "@topology/core";
import { getDataIdList } from "@/mqtt/msg";
var myTopology = null;

export default {
  name: "widgetTopology",
  components: {
    YTdialog,
    YKdialog,
    timeReport,
    YTdialogAll,
  },
  props: {
    value: Object,
    ispreview: Boolean,
    isShow: Boolean,
  },
  data() {
    return {
      topologyKey: 5000,
      FangZhenDialogVisible: false, //方阵
      uuid: "",
      locked: 0,
      options: {},
      optionsStyle: {}, // 样式
      optionsData: {}, // 数据
      optionsSetup: {},
      data: {},
      defDataId: "",
      dataId: "",
      subDataId: "",
      timer: null,
      materials: {
        system: [],
        user: [],
        topology: [],
      },
      topologyData: {},
      body: [],
      header: [],
      loadingShow: false,
      mySpecialId: "",
      bodyConfigList: [],
      getBodyData: false,
      FangZhenTitle: "",
      isFullscreen: false,
      DialogWidth: "60%",
      maxheight: 300,
      switchFlag: false,
      isFormat: { setup: { alarmColor: false } },
    };
  },
  computed: {
    transStyle() {
      //console.log("computed transStyle");
      return this.objToOne(this.options);
    },
    styleObj() {
      return {
        position: this.ispreview ? "absolute" : "static",
        width: this.transStyle.width + "px",
        height: this.transStyle.height + "px",
        left: this.transStyle.left + "px",
        top: this.transStyle.top + "px",
        background: this.transStyle.background,
        opacity: this.transStyle.transparency / 100,
      };
    },
  },
  watch: {
    value: {
      handler(val) {
        this.options = val;
        // this.transStyle = this.objToOne(this.options);
        this.optionsStyle = val.position;
        this.optionsData = val.data;
        this.optionsSetup = val.setup;
        this.setOptionsData();
      },

      deep: true,
    },

    isFullscreen() {
      this.isFullscreen
        ? (this.maxheight = window.innerHeight - 80)
        : (this.maxheight = 300);
    },
  },
  created() {
    this.initTopologyKey();
    // console.log("初始化", this.dataId, this.ConstId, this.isShow, this.value);
  },
  mounted() {
    // console.log("挂在");
    setMessageCallback(this.onMsg);
    this.options = this.value;
    this.optionsStyle = this.value.position;
    this.optionsData = this.value.data;
    this.optionsSetup = this.value.setup;
    this.setOptionsData();
  },
  destroyed() {
    if (this.timer != null) {
      clearTimeout(this.timer);
      this.timer = null;
    }

    removeMessageCallback(this.onMsg);

    if (myTopology != null) {
      myTopology.destroy();
      myTopology = null;
    }

    //console.log("widgetTopology destroyed, topology=", myTopology);
  },
  beforeDestroy() {
    this.getBodyData = false;
  },

  methods: {
    fullscreen() {
      this.isFullscreen = !this.isFullscreen;
    },
    initTopologyKey() {
      this.topologyKey = 1000 + Math.trunc(Math.random() * 1000);
    },
    getCellClassName({ row, column, rowIndex, columnIndex }) {
      // console.log(this.isFormat.setup.alarmColor);
      if (this.isFormat.setup.alarmColor) {
        if (columnIndex != 0) {
          const cellValue = row[columnIndex];
          if (cellValue !== 0) {
            return "GJ1";
          } else {
            return "";
          }
        }
      }
    },
    refreshPen() {
      let data = store.state.data;
      let keys = Object.keys(data);
      for (let idx = 0; idx < keys.length; idx++) {
        let key = keys[idx];
        let id = data[key].id;
        let value = data[key].value;
        let pens = myTopology.find(id, true, true);
        for (let i = 0; i < pens.length; i++) {
          DataMessage.refreshPen(myTopology, pens[i], value);
        }
      }
    },
    showTopologyView(bShow) {
      let pens = myTopology.data.pens;
      for (let i = 0; i < pens.length; i++) {
        pens[i].visible = bShow;
      }
      myTopology.render();
    },
    onSizeWindow() {
      myTopology.fitView(32);
      myTopology.render();
    },
    onSizeOri() {
      myTopology.open(this.data);
      myTopology.lock(true);
      this.showTopologyView(true);
      myTopology.render();
    },
    // 数据解析
    setOptionsData() {
      // console.log("topology组件监听到数据变化");
      if (!this.switchFlag) {
        if (myTopology != null) {
          // console.log("重置myTopology");
          myTopology.open({});
          this.data = {};
          myTopology.destroy();
          myTopology = null;
        }

        myTopology = new Topology("topology", {
          disableScale: true,
          disableTranslate: true,
        });

        const optionsData = this.optionsData; // 数据类型 静态 or 动态
        if (optionsData.dataType == "dynamicData") {
          if (optionsData.dynamicData.hasOwnProperty("chartProperties")) {
            if (
              optionsData.dynamicData.chartProperties.hasOwnProperty("dataId")
            ) {
              this.dataId = optionsData.dynamicData.chartProperties.dataId;
            }
          }
        } else {
          this.optionsData = optionsData.staticData;
        }

        this.defDataId = this.dataId;

        if (store.state.le5le.hasOwnProperty(this.defDataId)) {
          if (store.state.le5le[this.defDataId].hasOwnProperty("subDataId")) {
            this.subDataId = store.state.le5le[this.defDataId].subDataId;
          }
        }
        if (this.subDataId != "" && this.subDataId != this.dataId) {
          this.dataId = this.subDataId;
        }

        if (!this.isShow) {
          this.dataId = this.defDataId;
        }

        if (!store.state.le5le.hasOwnProperty(this.dataId)) {
          this.reqLe5LePage();
        } else if (!store.state.le5le[this.dataId].hasOwnProperty("data")) {
          this.reqLe5LePage();
        } else {
          let data = Object.assign({}, store.state.le5le[this.dataId].data);
          this.data = data;
          this.showLe5LePage();
        }

        getDataIdList();
      } else {
        this.switchFlag = false;

        if (!store.state.le5le.hasOwnProperty(this.dataId)) {
          this.reqLe5LePage();
        } else if (!store.state.le5le[this.dataId].hasOwnProperty("data")) {
          this.reqLe5LePage();
        } else {
          this.data = Object.assign({}, store.state.le5le[this.dataId].data);

          if (this.timer != null) {
            clearTimeout(this.timer);
            this.timer = null;
          }
          this.showLe5LePage();
        }
      }
    },

    showLe5LePage() {
      this.timer = setTimeout(() => {
        myTopology.open(this.data);
        myTopology.lock(true);
        myTopology.on("node", this.onNodeMessage);
        this.onSizeWindow();
        this.refreshPen();
      }, 50);
    },
    reqLe5LePage() {
      let newMsg = {
        webMsgType: 1016,
        funCode: 3,
      };
      newMsg.data = { id: this.dataId };
      this.mySpecialId = publishMsg(newMsg);
    },
    onMsg(topic, msg) {
      switch (msg.webMsgType) {
        case 1016:
          switch (msg.funCode) {
            case 3:
              if (msg.retCode != 0 || !msg.data) {
                this.$message.error(msg.retMsg);
              } else {
                if (msg.data.id == this.dataId) {
                  if (!store.state.le5le.hasOwnProperty(this.dataId)) {
                    store.commit("initLe5LeDataOnce", msg);
                  } else if (
                    !store.state.le5le[this.dataId].hasOwnProperty("data")
                  ) {
                    store.state.le5le[msg.data.id].data = msg.data.data;
                  }
                  this.data = msg.data.data;
                  this.showLe5LePage();
                }
              }
              break;
            case 6:
              if (msg.retCode != 0 || !msg.data) {
                this.$message.error(msg.retMsg);
              } else {
                if (msg.data.id == this.dataId) {
                  store.state.le5le[msg.data.id] = msg.data;
                  this.data = msg.data.data;
                  this.showLe5LePage();
                }
              }
              break;
            default:
              break;
          }
          break;
        case 1024:
          switch (msg.funCode) {
            case 7:
              if (this.mySpecialId == msg["specialId"]) {
                if (msg.retCode != 0 || !msg.data) {
                  this.$message.error(msg.retMsg);
                } else {
                  this.body = msg.data.body;
                  this.header = msg.data.header;
                  this.header.forEach((e) => {
                    if (e.unit) {
                      e.name = e.name + "(" + e.unit + ")";
                    }
                  });
                  this.loadingShow = false;
                  let id = msg.data.id;
                  //发送报表配置预览
                  let newMsg2 = {
                    webMsgType: 1024,
                    funCode: 8,
                  };
                  newMsg2.data = { id: id };
                  this.mySpecialId = publishMsg(newMsg2);
                }
              }
              break;
            case 8:
              // if (checkSpecialId) {
              if (msg.retCode != 0 || !msg.data) {
                this.$message.error(msg.retMsg);
              } else {
                this.bodyConfigList = msg.data.body;
                this.getBodyData = true;
              }
              // }
              break;
            default:
              break;
          }
          break;
        default:
          if (myTopology != null) {
            DataMessage.onMsg(myTopology, msg);
          }
          break;
      }
    },

    onNodeMessage(pen) {
      let penData = pen.data;
      if (penData != null) {
        const ctlData = penData;
        this.isFormat = ctlData;
        // this.FangzhenTitle = ctlData.name;
        ctlData.name
          ? (this.FangZhenTitle = ctlData.name)
          : (this.FangZhenTitle = this.FangZhenTitle);

        ctlData.width
          ? (this.DialogWidth = ctlData.width)
          : (this.DialogWidth = this.DialogWidth);

        switch (ctlData.ctrl_type) {
          case 0:
            {
              // console.log("遥控测试", ctlData);
              this.$refs.ykRef.Ykdialog(ctlData);
            }
            break;
          case 1:
            {
              this.$refs.ytRef.Ytdialog(ctlData);
            }
            break;
          case 2: //实时报表数据弹窗
            {
              this.getPerview(ctlData);
            }
            break;
          case 3: //全局遥调
            {
              this.$refs.ytallRef.Ytdialog(ctlData);
            }
            break;
          case 4: //切换显示一次图
            {
              this.$store.state.le5le[this.defDataId].subDataId = ctlData.id;
              this.dataId = ctlData.id;
              this.switchFlag = true;
              this.setOptionsData();
            }
            break;
        }
      }
    },
    getReqLe5LePage(val) {
      let newMsg = {
        webMsgType: 1016,
        funCode: 3,
      };
      newMsg.data = { id: val };
      // console.log(newMsg);
      this.mySpecialId = publishMsg(newMsg);
    },
    getPerview(val) {
      //发送报表实时预览
      this.FangZhenDialogVisible = true;
      let newMsg1 = {
        webMsgType: 1024,
        funCode: 7,
      };
      newMsg1.data = { id: val.id };
      this.mySpecialId = publishMsg(newMsg1);
      this.loadingShow = true;
    },
  },
};
</script>
<style lang="scss" scoped>
.topology {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

// ::v-deep .le5le-topology .myTopology div[id$="-myTopology"] {
::v-deep .le5le-topology .canvas div[id$="-canvas"] {
  background-color: transparent;
}

.preview {
  position: relative;
  // height: 100vh;
  // width: 100%;
  // height: 100%;
  // overflow: hidden;

  .tools {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    display: flex;

    & > div {
      flex-grow: 1;
    }
  }

  //   button {
  //     margin: 12px 16px;
  //   }
  // }
  // .topology {
  //   width: 100%;
  //   height: 100%;
  // }
}

::v-deep .v-modal {
  display: none;
}

::v-deep .mydialog .el-dialog__header {
  background-color: rgba(0, 15, 52) !important;
  padding: 5px 20px 5px !important;

  .el-dialog__headerbtn {
    top: 8px;
  }

  // .el-dialog__title {
  //   color: #0a74ff96 !important;
  //   font-weight: 600;
  // }
  .headertitle {
    span {
      color: #0a74ff96 !important;
      font-size: 16px;
      font-weight: 600;
    }

    i {
      float: right;
      margin-right: 25px;
      margin-top: 5px;
      cursor: pointer;
    }
  }
}

::v-deep .mydialog .el-dialog__body {
  background-color: #000f34;
  padding: 5px 20px;
}

::v-deep .mydialog {
  background: rgba(0, 15, 52);
}
::v-deep .GJ1 {
  animation: blinker 1s linear infinite;
  color: #ff4040;
  font-weight: bold; /*字体颜色为红色*/
}
</style>
